<template>
  <view class="page-container">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      :border="false"
      title="大额收款"
      fixed
      left-icon="back"
      @clickLeft="goBack"
    />

    <view class="content">
      <!-- 列表内容 -->
      <view class="list-content">
        <view
          v-for="item in orderList"
          :key="item.id"
          class="list-item"
          @click="handleItemClick(item)"
        >
          <view class="item-row">
            <text class="item-label">订单号：</text>
            <text class="item-value">{{ item.orderTradeId }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">金额：</text>
            <text class="item-value amount">¥ {{ item.totalAmount }}</text>
          </view>
          <view class="item-row">
            <text class="item-label">状态：</text>
            <text class="item-value" :class="getStatusClass(item.status)">
              {{ item.statusText }}
            </text>
          </view>
          <view class="item-row">
            <text class="item-label">创建时间：</text>
            <text class="item-value">{{ item.createTime }}</text>
          </view>
        </view>

        <!-- 加载更多组件 -->
        <LoadMore v-if="orderList.length > 0" :status="loadStatus" />

        <!-- 空状态 -->
        <Empty
          v-if="orderList.length === 0 && !listLoading"
          text="暂无订单数据"
        />
      </view>

      <!-- 创建按钮 -->
      <view class="create-button" @click="goToCreate">
        <text>创建</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { onReachBottom } from "@dcloudio/uni-app";
import { getBigReceiptOrderList } from "@/api/mine";
import { useUserStore } from "@/store/modules/user";
import { useStoreStore } from "@/store/modules/store";
import { useRequest } from "ahooks-vue";
import dayjs from "dayjs";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";
import Empty from "@/components/common/Empty/Empty.vue";

const userStore = useUserStore();
const storeStore = useStoreStore();

// 订单列表
const orderList = ref([]);

// 分页参数
const pagination = ref({
  offset: 1,
  limit: 10,
  total: 0,
});

// 加载状态
const loadStatus = ref("more"); // more, loading, noMore

// 获取订单列表
const { loading: listLoading, run: getOrderListRun } = useRequest(
  () => {
    return getBigReceiptOrderList({
      isMerchant: 1, // 商家订单
      merchantId: storeStore.storeId,
      userId: userStore.userId,
      offset: pagination.value.offset,
      limit: pagination.value.limit,
      plural: 5, // 5.大额收款订单
    });
  },
  {
    manual: true,
    onSuccess: (res) => {
      console.log("获取大额收款列表成功:", res);
      if (res && res.data && res.data.rows) {
        // 映射订单数据
        const newOrders = res.data.rows.map((item) => ({
          id: item.id, // 订单ID
          orderTradeId: item.orderTradeId || "", // 订单号
          createTime: item.tradeTime
            ? dayjs(item.tradeTime).format("YYYY-MM-DD HH:mm:ss")
            : "", // 订单创建时间
          totalAmount: (Number(item.tradeMoney) || 0).toFixed(2), // 交易金额
          status: getOrderStatus(item.tradeStatus), // 订单状态
          statusText: getOrderStatusText(item.tradeStatus), // 状态文本
          // 保留原始数据
          raw: item,
        }));

        // 如果是第一页，直接替换；否则追加
        if (pagination.value.offset === 1) {
          orderList.value = newOrders;
        } else {
          orderList.value = [...orderList.value, ...newOrders];
        }

        // 更新总数
        pagination.value.total = res.data.total || 0;

        // 更新加载状态
        if (orderList.value.length >= pagination.value.total) {
          loadStatus.value = "noMore";
        } else {
          loadStatus.value = "more";
        }
      }
    },
    onError: (err) => {
      console.error("获取大额收款列表失败:", err);
      loadStatus.value = "more";
    },
  }
);

// 获取订单状态
const getOrderStatus = (tradeStatus) => {
  switch (tradeStatus) {
    case 0:
      return "pending"; // 待支付
    case 1:
      return "pending"; // 待发货
    case 2:
      return "pending"; // 待收货
    case 3:
      return "cancelled"; // 已取消
    case 4:
      return "completed"; // 已完成
    default:
      return "unknown";
  }
};

// 获取订单状态文本
const getOrderStatusText = (tradeStatus) => {
  switch (tradeStatus) {
    case 0:
      return "待支付";
    case 1:
      return "待发货";
    case 2:
      return "待收货";
    case 3:
      return "已取消";
    case 4:
      return "已完成";
    default:
      return "未知";
  }
};

// 获取状态样式类
const getStatusClass = (status) => {
  switch (status) {
    case "completed":
      return "status-success";
    case "pending":
      return "status-pending";
    case "cancelled":
      return "status-reject";
    default:
      return "";
  }
};

// 刷新数据
const refreshData = () => {
  pagination.value.offset = 1;
  orderList.value = [];
  getOrderListRun();
};

// 加载更多
const loadMore = () => {
  if (loadStatus.value === "noMore" || loadStatus.value === "loading") {
    return;
  }

  loadStatus.value = "loading";
  pagination.value.offset += 1;
  getOrderListRun();
};

// 返回
const goBack = () => {
  uni.navigateBack();
};

// 跳转到创建页面
const goToCreate = () => {
  uni.navigateTo({
    url: "/pages/mine/largePayment/createOrder",
  });
};

// 处理列表项点击
const handleItemClick = (item) => {
  console.log("点击列表项:", item);
  // 跳转到详情页
  uni.navigateTo({
    url: `/pages/mine/largePayment/detail?id=${item.id}`,
  });
};

// 页面加载
onMounted(() => {
  console.log("大额收款页面加载完成");

  // 从本地缓存恢复店铺信息和用户信息
  storeStore.hydrateFromStorage();
  userStore.hydrateFromStorage();

  console.log("商户ID:", storeStore.storeId);
  console.log("用户ID:", userStore.userId);

  // 加载初始数据
  if (storeStore.storeId && userStore.userId) {
    refreshData();
  } else {
    console.warn("缺少商户ID或用户ID，无法加载订单列表");
    uni.showToast({
      title: "缺少必要信息，请先登录",
      icon: "none",
    });
  }
});

// 页面触底事件
onReachBottom(() => {
  loadMore();
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 20rpx 30rpx;
  padding-top: 20rpx;
}

// 列表内容
.list-content {
  min-height: 500rpx;
  margin-bottom: 120rpx;
}

.list-wrapper {
  width: 100%;
}

.list-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 20rpx;

  &:active {
    opacity: 0.9;
  }
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.item-label {
  font-size: 28rpx;
  color: #666;
  min-width: 160rpx;
}

.item-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;

  &.amount {
    color: #ff9900;
    font-weight: 600;
  }

  &.status-success {
    color: #4caf50;
  }

  &.status-pending {
    color: #ff9900;
  }

  &.status-reject {
    color: #f44336;
  }
}

// 创建按钮
.create-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  box-sizing: border-box;
  width: 700rpx;
  height: 88rpx;
  text-align: center;
  line-height: 88rpx;
  background-color: #fabc02;
  border-radius: 50rpx;

  text {
    font-size: 32rpx;
    color: #fff;
    font-weight: 600;
  }

  &:active {
    opacity: 0.8;
  }
}
</style>
